#include "StdAfx.h"
#include "PopupServerThread.h"
#include "popup.h"
#include "popupdlg.h"
#include "PopupServer.h"
#include <iostream>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

using namespace std;

IMPLEMENT_DYNCREATE(PopupServerThread, CWinThread)

BOOL PopupServerThread::InitInstance()
{
	return TRUE;
}

int PopupServerThread::Run()
{
	bool _exit = false;
	int _port = 2000;
	CpopupApp *_app = (CpopupApp*)AfxGetApp();
	_app->m_options.getIntOption(SERVER_PORT, _port);

	while (!_exit)
	{
		_app->popupdlg->ShowWindow(SW_HIDE);
		cout << "Starting server" << endl;	

		PopupServer *_server = PopupServer::getInstance(_port, 1024);
		_app->m_popupserver = _server;
		_server->run(); // Blocking call
		delete _server;
		_app->m_popupserver = 0;
		
		cout << "Server stopped" << endl;
		Sleep(5000);
	}

	return 0;
}

void PopupServerThread::kill()
{
	AfxEndThread(0);
}